import os  
import hashlib 
import json 
import time
import datetime
import util.chash
import modules.db
class CwebAppUtil:
    def __init__(self):
        pass 
    def __call__(self):
        return self
    
   
    @staticmethod
    def TimeStampToTime(timestamp):
        timeStruct = time.localtime(timestamp)
        return time.strftime('%Y-%m-%d %H:%M:%S',timeStruct)
   
    
    @staticmethod
    def getcardlists(user_id):
        cardlists=[]
        result=modules.db.Sqlite3Db.card_findByTel(user_id)
        if result!=None and len(result)>0:
            for index,row in enumerate(result):
                carinof={
                            'card':f'card{index+1}',
                            'number':row[0],
                            'createTime': row[4]
                        }
                cardlists.append(carinof)
            return cardlists
        else:
            return cardlists
  
               
    
    @staticmethod 
    def ifcardIsAlreadyStrored(user_id,keystr):
        address=util.ccrypto.CCrypto.getAddressFromKeystr(keystr)
        if address:
            result=modules.db.Sqlite3Db.card_findByAddress(address)
            if result!=None and len(result)>0:
                return True
            else:
                return False
        else:
            return False
    
    @staticmethod
    def produceNewCard(user_id):
        result= util.ccrypto.CCrypto.produceKey()
        modules.db.Sqlite3Db.card_add(result['address'],result['publickey'],result['privatekey'],user_id)
        return result
    
    @staticmethod
    def addCard(user_id,keystr):
        if CwebAppUtil.ifcardIsAlreadyStrored(user_id,keystr):
            return False
        else:
            result= util.ccrypto.CCrypto.addKey(keystr)
            if result!=None:
                return modules.db.Sqlite3Db.card_add(result['address'],result['publickey'],result['privatekey'],user_id)
            else:
                return False
        


   
